<?php


namespace App\Repositories\Services;


use App\Lib\Check\Authorize;
use App\Repositories\Contracts\ApiNodeRepository;
use App\Repositories\Eloquent\Api\ApiNodeModel;
use App\Repositories\Eloquent\Api\AppidModel;
use EasySwoole\Component\Singleton;

class ApiNode implements ApiNodeRepository
{
    use Singleton;
    use Authorize;
    protected $status;
    protected $_model_appid;
    protected $_model_url;
    // 错误信息
    public $errors = array(
        1=>'success',
        111 => 'appid 不存在',
        222 => 'jwt 验证失败 ',
        333 => '非法链接',
        555 => 'Request method error !',
        666 => '请先登录',
        777 => '登录验证失败，',
    );

    function __construct()
    {
        $this->_model_appid = new AppidModel();
        $this->_model_url = new ApiNodeModel();

    }

    //节点验证
    public function checkNode(string $url = '', string $method = '', string $ip = '', string $appid = '', string $jwt= '')
    {
        //jwt
        $appsecret = $this->_model_appid->getAppsecretByAppid($appid);
        if(empty($appsecret)){
            return $this->returnError(111);
        }
        $this->setConfig($appid,$appsecret);
        $jwtItem = $this->decryptToken($jwt);
        if($jwtItem['status'] < 0){
            return $this->returnError(222,$jwtItem['error']);
        }
        $user = $jwtItem['result']['user'];
        $appInfo = $jwtItem['result']['data'];
        // api url 验证
        $urlObj = $this->_model_url->getItemByUrl($url);
        if(empty($urlObj)){
            return $this->returnError(333,$url);
        }
        //验证请求
        if($method !=strtoupper($urlObj->method)){
            return $this->returnError(555);
        }
        //验证登录
        $memberItem = [];
        if($urlObj->islogin == 1){
             if($user == USER_SESSION_NOT_LOGIN){
                 return $this->returnError(666);
             }
             list($status,$msg,$memberItem) = Member::getInstance()->checkLogin($user);
             if($status != 1){
                 return $this->returnError(777,$msg);
             }
        }
        return $this->returnError(1,'',$memberItem,$appInfo);

    }


    public function returnError(int $index = 0,string $msg = '',array $adminItem = [],array $appInfo = []) {
        return [$index,$this->errors[$index].$msg,$adminItem,$appInfo];
    }

}